import common.CommonDemo;
import org.openqa.selenium.By;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import java.time.Duration;

public class ActionMouseDrag {

    private CommonDemo commonDemo;
    private String url;
    private WebDriver driver;

    @BeforeTest
    public void setUp() {
        try {
            commonDemo = new CommonDemo();
            url = commonDemo.getUserDir("src/main/resources/actionDrag.html");
            driver = commonDemo.getChromeDriver();
            driver.manage().window().maximize();
            driver.get(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 拖拽元素到指定位置
     */
    @Test
    public void dragAndDropElement() {
        WebElement element = driver.findElement(By.id("draggable"));
        WebElement element1 = driver.findElement(By.id("droppable"));
        new Actions(driver)
                .pause(Duration.ofSeconds(1))
                .dragAndDrop(element, element1)
                .perform();
    }

    /**
     * dragAndDropByOffset：以当前元素为原点，按照指定偏移量拖拽元素
     */
    @Test
    public void dragAndDropByOffset() {
        WebElement draggable = driver.findElement(By.id("draggable"));
        Rectangle start = draggable.getRect();
        Rectangle finish = driver.findElement(By.id("droppable")).getRect();
        System.out.println(finish.getX()+"::"+start.getX()+":::"+(finish.getX()-start.getX()));
        System.out.println(finish.getY()+"::"+start.getY()+":::"+(finish.getY()-start.getY()));
        new Actions(driver)
                .pause(Duration.ofSeconds(2))
                .dragAndDropBy(draggable, finish.getX() - start.getX(), finish.getY() - start.getY())
                .perform();
    }

    @AfterTest
    public void tearDown() {
        try {
            Thread.sleep(2000);
            driver.quit();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
